package com.example.servlet;

import com.example.bean.User;
import com.example.service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "LoginServlet", value = "/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.接收登录的信息 用户名和密码的获取
        String username = request.getParameter("username");
        System.out.println("获取到的用户名为:"+username);
        String password = request.getParameter("password");
        System.out.println("获取到的用户名为:"+password);

        //2.创建UserService类型的对象去实现数据的校验功能
        UserService userService=new UserService();
        User user = userService.userLoginService(new User(username, password));
        if(null==user){
            System.out.println("用户名或密码错误,登录失败!");
            request.setAttribute("error","登录失败,用户名或密码错误!");
            //实现服务器跳转 共享request和response对象
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("login.jsp");
            requestDispatcher.forward(request,response);
        }else{
            System.out.println("登录成功!");
            //将登录成功的用户信息放入session对象中实现多个请求的共享
            request.getSession().setAttribute("user",user);
            //实现客户端跳转
            response.sendRedirect("manage.jsp");
        }
    }
}
